package com.eascs.afterloan.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.o2o.internal.util.BaseUserUtil;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.form.AdvanceSettleForm;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.loan.vo.O2oRepaymentRecordVo;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.type.SystemModule;

@Controller
@RequestMapping("/advanceSettle")
public class AdvancedSettleController extends BaseMasterViewController {
	private static Logger logger = LoggerFactory.getLogger(AdvancedSettleController.class);
	@Autowired
	AdvanceSettleService advanceSettleService;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	BaseUserUtil userUtils;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Reference
	SysOrgService sysOrgService;
	@Autowired
	private BaseUtils baseUtils;

	@Override
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "AdvanceSettle");
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/list")
	public String list(AdvanceSettleForm entity) {
		entity.setPageSize(10);
		String url = "/advanceSettle/list";
		String advancePaymentReportUrl = "/advanceSettle/download";
		if (null != entity) {
			String billCode = entity.getBillCode() == null ? "" : entity.getBillCode();
			String name = entity.getLoanerName() == null ? "" : entity.getLoanerName();
			url = UrlUtil.appendUrl(url, "billCode", billCode);
			url = UrlUtil.appendUrl(url, "loanerName", name);
			String jqstartdate = entity.getJqstartdate() == null ? "" : entity.getJqstartdate();
			String jqenddate = entity.getJqenddate() == null ? "" : entity.getJqenddate();
			advancePaymentReportUrl = UrlUtil.appendUrl(advancePaymentReportUrl, "bill_code", billCode);
			advancePaymentReportUrl = UrlUtil.appendUrl(advancePaymentReportUrl, "name", name);
			advancePaymentReportUrl = UrlUtil.appendUrl(advancePaymentReportUrl, "jqstartdate", jqstartdate);
			advancePaymentReportUrl = UrlUtil.appendUrl(advancePaymentReportUrl, "jqenddate", jqenddate);
			url = url + "&showO2oPage=";
		} else {
			url = url + "?showO2oPage=";
		}
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setUsersno(no);
		PageResult<Object[]> pageResult = advanceSettleService.findByPageList(entity);
	
		String[] titles = { "单据号", "借款人姓名","付款人","付款时间" ,"结清时间","状态"};
		Button[] findButton = new Button[] { ButtonHelper.createOpenButton(null, "/advanceSettle/advancedPaymentView?billCode=billCode&referId=") };
		/*Button star = ButtonHelper.createAjaxButton("启动流程", "/advanceSettleRest/advancedPaymentStartUp?referId=");
		star.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object arg0) {
				Object []param = (Object[]) arg0;
				if(param[3].equals("新建")){
					return true;
				}
				return false;
			}
		});
		Button[] startButton = new Button[] {star};*/
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setTitleButtons(findButton);
		//paginationInfo.setMoreButtons(startButton);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(1);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", entity);
		ViewContext.put("advancePaymentReportUrl", advancePaymentReportUrl);
		return "/advance/index";
	}
	
	
	
	@RequestMapping("/download")
	public void dowanload(AdvanceSettleForm entity,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		entity.setPageSize(Integer.MAX_VALUE);
		entity.setType("1");
		PageResult<Object[]> pageResult =advanceSettleService.findByPageList(entity);
		String path = AdvancedSettleController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/advance-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "提前还款结清列表.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), AdvancedSettleController.class.getResourceAsStream("/excelTemplate/advance-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
//		return result;
	}
	
	/* * 流程中审核的详情页面
	 * @param entity
	 * @return
	 */
	@RequestMapping("/advancedPaymentView")
	public String advancedPaymentView(O2oRepaymentRecordVo entityVo) {

		
		String type = entityVo.getType();
		AdvancedPayment advancedPayment = null;
		String billCode = "";
		if (type == null && entityVo.getReferId() != null) { // 如果type没有值说明是查看
			advancedPayment = advanceSettleService.queryById(entityVo.getReferId());
			billCode = advancedPayment.getBillCode();
		} else {
			billCode = entityVo.getBillCode();
			
		}
		
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.fingByBillCode(billCode);
		if(type!=null){
			advancedPayment=advanceSettleService.queryEntity(loanapply.getLoanapplyNo(),null);
		}	

		ViewContext.put("type", type);
		if(type!=null && type.equals("1")){
			
			String approvalUrl = baseUtils.getApprovalUrl(entityVo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
			ViewContext.put("approvalUrl", approvalUrl);
		}else
		{
			String agreeUrl = baseUtils.getApprovalAgreeUrl(advancedPayment.getLoanapplyNo(), null, SystemModule.SYSTEM_MODULE_O2O);
			ViewContext.put("agreeUrl", agreeUrl);
		}
		logger.info("工作流访问回款详情：参数billCode：【{}】", billCode);

		O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanapply.getLoanId(), loanapply.getLoanapplyNo());
		ViewContext.put("advancedPayment", advancedPayment);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("materEntity", materEntity);

		queryDataList(loanapply.getLoanapplyNo());
		String 	url = "advance/advance_payment_approval_new";
		
		return url;

	}
	
	/**
	 * @Title: queryDataList
	 * @Description: 提前还款附件列表
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @return void
	 * @throws
	 * @date 2017年6月13日 下午4:22:05
	 */
	public void queryDataList(String loanapplyNo) {
		String code="TQHK" ;//提前还款附件
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
}
